package com.bread.tliaswebmanagement.aop;

import com.bread.tliaswebmanagement.mapper.EmpLoginLogMapper;
import com.bread.tliaswebmanagement.pojo.Emp;
import com.bread.tliaswebmanagement.pojo.EmpLoginLog;
import com.bread.tliaswebmanagement.pojo.LoginResult;
import com.bread.tliaswebmanagement.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class EmpLoginLopAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.bread.tliaswebmanagement.service.impl.EmpServiceImpl.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long begin = System.currentTimeMillis();

        LoginResult result = (LoginResult) joinPoint.proceed(); // 登录结果

        Emp init = (Emp) CurrentHolder.get(); // 请求中携带的用户名和密码
        String username = init.getUsername();
        String password = init.getPassword();
        Short status = 0;
        String jwt = null;
        if (result != null) {
            jwt = result.getToken();
            status = 1;
        }
        long end = System.currentTimeMillis();
        empLoginLogMapper.insert(new EmpLoginLog(null, username, password, LocalDateTime.now(), status, jwt, end - begin));
        CurrentHolder.remove();
        log.info("移除ThreadLocal中的登录请求信息");
        return result;
    }

}
